package cn.tedu._10article.controller;

import cn.tedu._10article.base.pojo.dto.UserArticleParam;
import cn.tedu._10article.base.pojo.dto.UserLoginParam;
import cn.tedu._10article.base.pojo.entity.Article;
import cn.tedu._10article.base.pojo.vo.ArticleVO;
import cn.tedu._10article.base.pojo.vo.UserVO;
import cn.tedu._10article.base.response.JsonResult;
import cn.tedu._10article.base.response.StatusCode;
import cn.tedu._10article.mapper.ArticleMapper;
import cn.tedu._10article.mapper.UserMapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Tag(name="01用户模块")
@Slf4j
@Validated
@RestController
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;
/*
1.登录功能
 */
    @PostMapping(value = "login")
    @Operation(summary = "登录功能")
    @ApiOperationSupport(order = 10)
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, HttpSession session) {
        log.debug("登录功能参数"+userLoginParam);
        UserVO userVO=userMapper.selectUserByUsernameAndPassword(userLoginParam);
        if(userVO==null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }else {
            //存储会话标识
            session.setAttribute("user",userVO);
            return JsonResult.ok(userVO);
        }
    }
    /*
    2.发表文章功能
     */
    @PostMapping(value = "article")
    @Operation(summary = "发表文章功能")
    @ApiOperationSupport(order = 20)
    public JsonResult article(@RequestBody @Validated UserArticleParam userArticleParam, HttpSession session) {
        log.debug("发表文章功能"+userArticleParam);
        //获取会话标识,用于获取用户id;
        UserVO userVO=(UserVO) session.getAttribute("user");
        //存入数据
        Article article=new Article();
        BeanUtils.copyProperties(userArticleParam,article);
        article.setUerId(userVO.getId());
        //调用接口
        userMapper.insertArticle(article);
        return JsonResult.ok();
    }
    /*
    3.查询指定文章功能
     */
    @GetMapping("seleceByArticleId")
    @Operation(summary = "查询指定文章功能")
    @ApiOperationSupport(order = 30)
    @Parameter(name="id",description = "文章id",required = true)
    public JsonResult seleceArticle(@Range(min = 1,max = 100,message = "文章id范围1-100") Long id) {
        log.debug("查询指定文章功能参数"+id);
        ArticleVO articleVO=userMapper.selectArticleById(id);
        return JsonResult.ok(articleVO);
    }
}
